package com.rw.utils;

import org.springframework.beans.factory.DisposableBean;

import java.sql.*;

/**
 * 数据源工具
 * @author rabit
 */
public class DataSource{

    private String url;
    private String userName;
    private String password;

    private Connection conn;
    private Statement st;
    private ResultSet rs;

    public DataSource(String url, String userName, String password) throws ClassNotFoundException, SQLException {
        this.url = url;
        this.userName = userName;
        this.password = password;
        //1.加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.构建连接
        this.conn = DriverManager.getConnection(this.url, this.userName, this.password);
        //3.	向数据库发送sql
        this.st = conn.createStatement();
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Connection getConn() {
        return conn;
    }

    public void setConn(Connection conn) {
        this.conn = conn;
    }

    public ResultSet selectData(String sql) throws SQLException {
        this.rs = this.st.executeQuery(sql);
        return this.rs;
    }

    public int updateData(String sql) throws SQLException {
        int num = this.st.executeUpdate(sql);
        return num;
    }


    public void closed() throws SQLException {
        //4.关闭连接
        this.conn.close();
        this.st.close();
        if (this.rs!= null){
            this.rs.close();
        }
        System.out.println("数据库链接已关闭");
    }

    public void init(){
        System.out.println("初始化");
    }

}
